package com.game.level;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import com.game.objects.Environment;
import com.jme.math.Vector3f;

public class LevelLoader extends Thread {
	
	private String name;
	private List<Element> terrainElements;
	private ListIterator<Element> next;
	private int preLoad;
	Environment env;
	private boolean running=true;
	private boolean ready=false; 
	private Document doc;
	
	ArrayList<Terrain> blocks;
	@SuppressWarnings("unchecked")
	public LevelLoader(Environment env, String file, int preLoad){
		super("Loader");
		this.env=env;
		this.preLoad=preLoad;
		SAXBuilder builder = new SAXBuilder();
		try {
			doc = builder.build(LevelLoader.class.getClassLoader()
					.getResourceAsStream("com/data/level/"+file));
			Element root = doc.getRootElement();
			name = root.getAttributeValue("title");
			terrainElements = root.getChildren("block");
			
			next=terrainElements.listIterator();
			
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		startAndWait();
	}
	
	private void startAndWait(){
		start();
		while(!ready){
			try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public boolean hasNext(){
		return next.hasNext();
	}

	public void run(){
		setPriority(Thread.MIN_PRIORITY);
		int i=0;
		float pos = 128;
		while(running && hasNext() ){
			if(i==preLoad){
				ready=true;
			}
			Terrain terra = new Terrain(next.next());
			terra.setUp(env);
			terra.getLocalTranslation().subtractLocal(Vector3f.UNIT_Z.mult(pos));
			env.getEnvironment().attachChild(terra);
			pos+=128*5;
			i++;
		}
		System.out.println("Alles geladen");
		close();
	}
	

	public void close() {
		running=false;
	}
}